package com.lgx.mobile.rest.group;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.exception.DataException;
import com.lgx.mobile.entity.Group;
import com.lgx.mobile.service.IGroupService;
import com.lgx.right.entity.User;
import com.lgx.right.entity.UserExpand;
import com.lgx.right.service.IUserService;

/**
 * 
 * @author xuyichen
 *
 */
@Controller
@RequestMapping("/updateGroup")
public class UpdateGroupController {
	
	private static final Logger logger = Logger.getLogger(UpdateGroupController.class);

	@Autowired
	IGroupService groupService;

	public IGroupService getGroupService() {
		return groupService;
	}
	
	@Autowired
	IUserService userService;

	public IUserService getUserService() {
		return userService;
	}

	/**
	 * 圈子修改
	 * @param id id is key
	 * @param name name is key
	 * @param description description is key
	 * @param categoryId categoryId is key
	 * @return 0：失败；1：成功；2：圈子不存在；3：参数异常，有参数为空
	 */
	@RequestMapping(value="/{id}/{name}/{description}/{categoryId}",method=RequestMethod.GET)
	@ResponseBody
	public Object getGroup(@PathVariable("id") String id,@PathVariable("name") String name,
							@PathVariable("description") String description,@PathVariable("categoryId") String categoryId){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(name)
				&&StringUtils.isNotBlank(description)&&StringUtils.isNotBlank(categoryId)){
			Group group = getGroupService().findGroupById(Long.parseLong(id));
			if(group != null){
				String status = "0";
				group.setName(name);
				group.setDescription(description);
				group.setCategoryId(Long.parseLong(categoryId));
				try {
					getGroupService().updateGroup(group);
					status = "1";
				} catch (DataException e) {
					e.printStackTrace();
				}
				return status;
			}else{
				if(logger.isDebugEnabled()){
					logger.debug("updateGroup faild name and description and categoryId is error");
				}
//				"updateGroup faild please check group is exists";
				return "2";
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("updateGroup faild name and description and categoryId is not filled");
			}
//		    "updateGroup faild please check name and description and categoryId is filled";
			return "3";
		}
	}
	
	/**
	 * 圈子增加、删除人
	 * @param id id is key
	 * @param userId userId is key
	 * @param type type is key
	 * 			delete--删除人，add--增加人
	 * @return 0：失败；1：成功；2：该用户不是该圈子成员；3：用户不存在；4：圈子不存在；5：参数异常，有参数为空；
	 * 			6：该用户已经是该圈子成员；7:用户不存在；8：圈子不存在；9：请检查参数——type是否输入错误
	 */
	@RequestMapping(value="/{id}/{userId}/{type}",method=RequestMethod.GET)
	@ResponseBody
	public Object operateUserFromGroup(@PathVariable("id") String id,@PathVariable("userId") String userId,@PathVariable("type") String type){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(type)){
			//圈子删除人
			if(type.equals("delete")){
				Group group = getGroupService().findGroupById(Long.parseLong(id));
				if(group != null){
					User user = getUserService().findUserById(Long.parseLong(userId));
					if(user != null){
						//判断该用户是否应存在于该圈子中
						boolean bool = false;
						User u = new User(); 
						Object[] users = group.getUsers().toArray();
						for(int i=0;i<users.length;i++){
							if( ((User)users[i]).getId() ==  Long.parseLong(userId) ){
								bool = true;
								u = (User)users[i];
							}
						}
						if(bool){
							String status = "0";
							group.getUsers().remove(u);
							try {
								getGroupService().updateGroup(group);
								status = "1";
							} catch (DataException e) {
								e.printStackTrace();
							}
							return status;
						}else{
							if(logger.isDebugEnabled()){
								logger.debug("deleteUserFromGroup faild userId is error");
							}
//							"deleteUserFromGroup faild user is not in group";
							return "2";
						}
					}else{
						if(logger.isDebugEnabled()){
							logger.debug("deleteUserFromGroup faild userId is error");
						}
//						"deleteUserFromGroup faild please check user is exists";
						return "3";
					}
				}else{
					if(logger.isDebugEnabled()){
						logger.debug("deleteUserFromGroup faild id is error");
					}
//					"deleteUserFromGroup faild please check group is exists";
					return "4";
				}
			}
			//圈子添加人
			else if(type.equals("add")){
				Group group = getGroupService().findGroupById(Long.parseLong(id));
				if(group != null){
					User user = getUserService().findUserById(Long.parseLong(userId));
					if(user != null){
						//判断该用户是否应存在于该圈子中
						boolean bool = false;
						Object[] users = group.getUsers().toArray();
						for(int i=0;i<users.length;i++){
							if( ((UserExpand)users[i]).getUser().getId() ==  Long.parseLong(userId) ){
								bool = true;
							}
						}
						if(!bool){
							String status = "0";
							group.getUsers().add(user);
							try {
								getGroupService().updateGroup(group);
								status = "1";
							} catch (DataException e) {
								e.printStackTrace();
							}
							return status;
						}else{
							if(logger.isDebugEnabled()){
								logger.debug("addUserInGroup faild userId is error");
							}
//							"addUserInGroup faild user is already in group";
							return "6";
						}
					}else{
						if(logger.isDebugEnabled()){
							logger.debug("addUserInGroup faild userId is error");
						}
//						"addUserInGroup faild please check user is exists";
						return "7";
					}
				}else{
					if(logger.isDebugEnabled()){
						logger.debug("addUserInGroup faild id is error");
					}
//					"addUserInGroup faild please check group is exists";
					return "8";
				}
			}else{
//				"addUserInGroup faild please check type is filled";
				return "9";
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("addUserInGroup faild id and userId and type is not filled");
			}
//		    "addUserInGroup faild please check id and userId and type is filled";
			return "5";
		}
	}
}
